import { webConfig } from "../tools/webConfig";

export default class ImageManager {

    static manager: ImageManager;

    public images: Array<imageDictData>;
    imagesCount: Array<imageLibMaxData> = [
        { id: 'back', count: 4, extension: 'jpg' },
        { id: 'texture', count: 1, extension: 'png' },
    ];

    public constructor() {
        ImageManager.manager = this;
        this.images = [];

        webConfig.get().then(res => {
            this.imagesCount[0].count = res.background.count;
        });
    }

    public static async get(libId: string, imageName: string) {
        const { images } = ImageManager.manager;
        if (!libId || !imageName) return;
        let dict: Array<imageData> = images.find(u => u.id == libId)?.imageDict!;
        if (!dict) {
            dict = [];
            images.push({ id: libId, imageDict: dict });
        }

        let image: HTMLImageElement = dict.find(u => u.id == imageName)?.image!;
        if (!image) {
            image = await ImageManager.loadImage(imageName, libId) as HTMLImageElement;
            dict.push({ id: imageName, image: image });
        }
        return image;
    }

    public static async getRandomImage(libId: string) {
        const { imagesCount } = ImageManager.manager;
        if (!libId) return;

        const count = imagesCount.find(u => u.id == libId)?.count!;
        const index = (Number)(parseInt((Math.random() * count).toString()));
        const image = await ImageManager.get(libId, index.toString().padStart(2, '0'));
        return image;
    }

    public static async getNextImage(d: string, image: HTMLImageElement) {
        const { imagesCount } = ImageManager.manager;
        const name = ImageManager.getImageName(image);
        let nextIndex = (Number)(name) + 1;
        const maxCount = imagesCount.find(u => u.id == d)?.count!;
        if (nextIndex >= maxCount) {
            nextIndex = 0;
        }
        return await ImageManager.get(d, nextIndex.toString().padStart(2, '0'));
    }

    public static getImageName(Image: HTMLImageElement) {
        const path = Image.src;
        const last = path.lastIndexOf('/');
        const n = path.substring(last + 1, last + 3);
        return n;
    }

    public static async loadImage(name: string, d: string): Promise<unknown> {
        const { imagesCount } = ImageManager.manager;
        const image = new Image();
        const extension = imagesCount.find(u => u.id == d)?.extension;
        const path = await import(`../assets/images/${d}/${name}.${extension}`);
        image.src = path.default;
        return new Promise((rs, _rj) => {
            image.onload = () => {
                rs(image);
            }
        });
    }
}

interface imageDictData {
    id: string,//libId
    imageDict: Array<imageData>,
}

interface imageData {
    id: string,//imageName
    image: HTMLImageElement,
}

interface imageLibMaxData {
    id: string,//libId
    count: number,
    extension: string,
}